package net.lzzy.lxq.config;

import com.google.gson.JsonObject;
import net.lzzy.lxq.entities.AdminUser;
import net.lzzy.lxq.server.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AdminUserService service;
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        List<AdminUser> users=service.getUsers();
        for (AdminUser adminUser:users){
            auth.inMemoryAuthentication()
                    .withUser(adminUser.getUserId())
                    .password(adminUser.getPassword())
                    .roles("admin");
        }
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("admin")
                .and()
                .formLogin()
                .loginProcessingUrl("/admin_login")
                .loginPage("/login.html")
                .usernameParameter("account")
                .passwordParameter("password")
                .successHandler(new SuccessHandler())
                .failureHandler(new FailureHandler())
                .permitAll()
                .and().csrf().disable()
                .logout()
                .logoutUrl("/admin/logout")
                .invalidateHttpSession(true)
                .clearAuthentication(true);
    }
}
class SuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        JsonObject result=new JsonObject();
        result.addProperty("code",0);
        result.addProperty("redirect","/admin/admin.html");
        result.addProperty("msg","登录成功");
        PrintWriter writer=httpServletResponse.getWriter();
        writer.write(result.toString());
        writer.flush();
        writer.close();
        System.out.println("登录成功"+result.toString());
    }
}
class FailureHandler implements AuthenticationFailureHandler{

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        JsonObject result=new JsonObject();
        result.addProperty("code",1);
        result.addProperty("msg","登录失败："+e.getMessage());
        PrintWriter writer=httpServletResponse.getWriter();
        writer.write(result.toString());
        writer.flush();
        writer.close();
        System.out.println("登录失败"+e.getMessage());
    }
}